package com.myhome.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.alicloud.sms.ISmsService;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myhome.mapper.SmsMapper;
import com.myhome.domain.Sms;
import com.myhome.service.SmsService;
/**
*@Author QYiXin 
* @Date 2021 10 16 14 36
**/
@Service
public class SmsServiceImpl extends ServiceImpl<SmsMapper, Sms> implements SmsService{
    @Autowired
    ISmsService iSmsService;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public Boolean sendMessage(Sms sms) {
        System.out.println(JSON.toJSONString(sms));
        SendSmsRequest request = buildSmsRequest(sms);
        try {
            SendSmsResponse sendSmsResponse = iSmsService.sendSmsRequest(request);
            String code = sendSmsResponse.getCode();
            if ("OK".equals(code)) {
                sms.setStatus(1);
                return this.save(sms);
            }

        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

    private SendSmsRequest buildSmsRequest(Sms sms) {
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(sms.getMobile());
        request.setSignName("QYIXIN商城");
        request.setTemplateCode("SMS_226400280");
        String code = RandomUtil.randomNumbers(6);
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
        redisTemplate.opsForValue().set("SMS" + "SMS_226400280" + sms.getMobile(), code, 3, TimeUnit.MINUTES);
        sms.setContent(code);
        return request;
    }
}
